# 创建时间:2024/9/21 下午6:35
# 创建人:天霄
# 基于 Python 3.11
# ========================================
# 邮件助手
# ========================================
from pathlib import Path
import smtplib
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class EMailer:
    def __init__(self, mail_host: str, mail_username: str, mail_auth_password: str):
        """邮件发送助手

        :param mail_host: 邮件服务器地址（如：smtp.126.com）
        :param mail_username: 邮箱全名（xx@yy.zz）
        :param mail_auth_password: 授权密码
        """
        self.mail_host = mail_host  # 设置服务器
        self.mail_username = mail_username  # 用户名
        self.mail_auth_password = mail_auth_password  # 授权密码

    def send_email(self, receivers, subject, mail_msg, mail_type='plain', sender=None, attachments=None):
        """发送邮件

        :param receivers: 收件人（单个或多个，多个以逗号分隔）
        :param subject: 邮件主题
        :param mail_msg: 邮件内容，支持html
        :param mail_type: 邮件类型，html/plain
        :param sender: 发送人，默认为邮件发送者地址
        :param attachments: 多个附件路径，列表，默认无
        :type receivers: str
        :type attachments: list
        :return: 发送邮件是否成功
        """
        message = MIMEMultipart()
        message['From'] = sender or self.mail_username
        message['To'] = receivers
        message['Subject'] = subject
        message.attach(MIMEText(mail_msg, mail_type, 'utf-8'))

        if attachments:
            for atta in attachments:
                atta_path = Path(atta)
                if not atta_path.exists():
                    continue
                per_att = MIMEBase('application', 'octet-stream')
                per_att.set_payload(atta_path.read_bytes())
                encoders.encode_base64(per_att)
                filename = Header(atta_path.name, 'utf-8').encode()
                per_att.add_header("Content-Disposition", f'attachment; filename={filename}')
                # per_att = MIMEText(open(atta, 'rb').read(), 'base64', 'utf-8')
                # per_att = MIMEText(pathlib.Path(atta).read_text(), 'base64', 'utf-8')
                # per_att["Content-Type"] = 'application/octet-stream'
                # 这里的filename可以任意写，写什么名字，邮件中显示什么名字
                # per_att["Content-Disposition"] = f'attachment; filename={atta_path.name}'
                message.attach(per_att)

        try:
            smtpObj = smtplib.SMTP(self.mail_host, 25)  # 生成smtpObj对象，使用非SSL协议端口号25
            smtpObj.login(self.mail_username, self.mail_auth_password)  # 登录邮箱
            smtpObj.sendmail(self.mail_username, receivers.split(','), message.as_string())  # 发送给1人或多人
        except Exception as err:
            print(f'【Error】: 邮件发送失败！错误：{err.__class__.__name__}: {err}')
            return False
        else:
            print('邮件发送成功！')
            smtpObj.quit()
            return True
